package com.example.work_notebook;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;

import java.io.File;
import java.io.IOException;

import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

public class AddActivity extends AppCompatActivity {
    private EditText addTitle;
    private Button addSave;
    private EditText addData;
    private TextView showLocation;
    private static final int IMAGE_REQUEST_CODE = 1000;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE2 = 1001;
    private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 2000;
    private ImageView showImage;
    private VideoView showVideo;
    public AMapLocationClient mLocationClient = null;
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    String s = amapLocation.getProvince();//省信息
                    String s1 =  amapLocation.getCity();//城市信息
                    String s2 =  amapLocation.getDistrict();//城区信息
                    showLocation.setText(s1+s2);
                    Log.e("city",s1+s2);
                }else {
                    Log.e("AmapError","location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }
    };
    public AMapLocationClientOption mLocationOption = null;
    private Uri fileUri;
    private String path;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        showImage = findViewById(R.id.show_image);
        showVideo = findViewById(R.id.show_video);
        initAddFloatButton();
        initAddTata();
    }

    private void initAddTata() {
        addTitle = findViewById(R.id.add_title);
        addData = findViewById(R.id.add_data);
        addSave = findViewById(R.id.add_save);
        showLocation = findViewById(R.id.show_location);
        addSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String picPath = path;
                BmobFile bmobFile = new BmobFile(new File(picPath));
                String title = addTitle.getText().toString();
                String data = addData.getText().toString();
                notebook note = new notebook();
                note.setTitle(title);
                note.setContent(data);
                note.setVideoPath(fileUri+"");
                note.setLocation(showLocation.getText().toString());
                note.save(new SaveListener<String>() {
                    @Override
                    public void done(String s, BmobException e) {
                        if (e == null) {
                            Toast.makeText(AddActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                            Intent intent = new Intent(AddActivity.this, MainActivity.class);
                            startActivity(intent);
                        } else {
                            Log.e("AddActivity", "保存失败");
                        }
                    }
                });
            }
        });
    }

    private void initAddFloatButton() {
        FloatingActionButton delete = (FloatingActionButton) findViewById(R.id.add_delete);
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(AddActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(AddActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });
        FloatingActionButton videoPath = (FloatingActionButton) findViewById(R.id.add_videoPath);
        //视频
        videoPath.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(AddActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //权限还没有授予，需要在这里写申请权限的代码
                    ActivityCompat.requestPermissions(AddActivity.this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_CALL_PHONE2);
                } else {
                    //权限已经被授予，在这里直接写要执行的相应方法即可
                    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                    try {
                        fileUri = Uri.fromFile(createMediaFile()); // create a file to save the video
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);  // set the image file name
                    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high
                    // start the Video Capture Intent
                    startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
                }

            }
        });
        FloatingActionButton location = (FloatingActionButton) findViewById(R.id.add_location);
        //定位
        location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mLocationClient = new AMapLocationClient(getApplicationContext());
                mLocationClient.setLocationListener(mLocationListener);
                mLocationOption = new AMapLocationClientOption();
                AMapLocationClientOption option = new AMapLocationClientOption();
                /**
                 * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
                 */
                option.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
                if(null != mLocationClient){
                    mLocationClient.setLocationOption(option);
                    //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
                    mLocationClient.stopLocation();
                    mLocationClient.startLocation();
                }
                mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
                mLocationOption.setNeedAddress(true);
                mLocationOption.setHttpTimeOut(20000);
                mLocationOption.setInterval(5000);
                mLocationClient.setLocationOption(mLocationOption);
                mLocationClient.startLocation();
            }
        });
        FloatingActionButton audio = (FloatingActionButton)findViewById(R.id.add_audio);
        //音频
        audio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        FloatingActionButton image = (FloatingActionButton)findViewById(R.id.add_image);
        //图片
        image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(AddActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED)
                {
                    //权限还没有授予，需要在这里写申请权限的代码
                    ActivityCompat.requestPermissions(AddActivity.this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_CALL_PHONE2);
                }else {
                    //权限已经被授予，在这里直接写要执行的相应方法即可
                    Intent intent3 = new Intent(Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent3,IMAGE_REQUEST_CODE);
                }
            }
        });
        FloatingActionButton append = (FloatingActionButton)findViewById(R.id.add_append);
        append.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(AddActivity.this,"附件",Toast.LENGTH_SHORT).show();
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch(requestCode){
            //图片
            case IMAGE_REQUEST_CODE:
                if(resultCode == Activity.RESULT_OK && data != null){
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(selectedImage,
                            filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
                    cursor.moveToFirst();
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    path = cursor.getString(columnIndex);  //获取照片路径
                    cursor.close();
                    Bitmap bitmap = BitmapFactory.decodeFile(path);
                    showImage.setImageBitmap(bitmap);
                    Log.e("AddActivity",path);
                }
                break;
                //视频
            case CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE:
                if (resultCode == RESULT_OK) {
                    Toast.makeText(this, "视频已存储到本地:\n" +
                            data.getData(), Toast.LENGTH_LONG).show();
                    showVideo.setVideoURI(fileUri);
                    showVideo.requestFocus();
                    showVideo.start();
                    Log.e("videoUri",fileUri+"");
                }
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE2){
            if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
            }else{
                Toast.makeText(AddActivity.this, "你还未同意使用相册权限！", Toast.LENGTH_SHORT).show();
            }
        }
    }
    private File createMediaFile() throws IOException {
            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_MOVIES), "CameraDemo");
            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    Log.d("AddActivity", "failed to create directory");
                    return null;
                }
            }
            // Create an image file name
            long time = System.currentTimeMillis();
            String imageFileName = "VID"+time;
            String suffix = ".mp4";
            File mediaFile = new File(mediaStorageDir + File.separator + imageFileName + suffix);
            return mediaFile;
    }
}
